package ch.sfug.net.loader {
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import ch.sfug.net.loader.AbstractLoader;	

	/**
	 * @author loop
	 */
	public class VarsLoader extends AbstractLoader {

		private var ul:URLLoader;

		public function VarsLoader( req:URLRequest = null ) {
			super(req);
			ul = new URLLoader();
			ul.dataFormat = URLLoaderDataFormat.VARIABLES;
			ul.addEventListener(Event.COMPLETE, onLoaded);
			ul.addEventListener(Event.OPEN, onLoadStarts);
			ul.addEventListener(HTTPStatusEvent.HTTP_STATUS, delegate);
			ul.addEventListener(ProgressEvent.PROGRESS, delegate);
			ul.addEventListener(SecurityErrorEvent.SECURITY_ERROR, delegate);
			ul.addEventListener(IOErrorEvent.IO_ERROR, delegate);
		}

		
		public override function load( request:URLRequest = null ):void {
			this.request = request;
			ul.data = null;
			ul.load(this.request);
		}

		
		/**
		 * sends additional vars to the request
		 */
		public function send( vars:URLVariables, method:String = URLRequestMethod.POST ):void {
			if( request == null ) {
				throw new Error("you have to specify first a request before sending vars to this request");
			} else {
				request.data = vars;
				request.method = method;
				load();
			}
		}

		
		/**
		 * returns the xml
		 */
		public function getResult():* {
			return ul.data;
		}

		
		/**
		 * called when the loader has finished loading
		 */
		private function onLoaded( e:Event ):void {
			super.onLoadEnds(e);
		}

		
		/**
		 * simply delegates the events outside
		 */
		private function delegate( e:Event ):void {
			dispatchEvent(e);
		}
		
		override public function get bytesLoaded():Number
		{
			return ul.bytesLoaded;
		}
		override public function get bytesTotal():Number
		{
			return ul.bytesTotal;
		}
	}
}
